package com.exposit.books.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.exposit.books.domain.Order;
import com.exposit.books.service.OrderService;

@Controller
@RequestMapping("/admin")
public class AdminDispatchInOfficeOrdesController {

	@Autowired
	private OrderService orderService;

	
	@RequestMapping(value = "/adispatchinoffice", method = { RequestMethod.GET })
	public String adispatchinoffice(Model model) {

		final Long countOfOrders = 3L;
		model.addAttribute("countOfOrders", countOfOrders);

		List<Order> listOrder = orderService.getAll();
		List<Order> partlyOrders = new ArrayList<Order>();

		for (int i = 0; i < listOrder.size(); i++) {
			if (listOrder.get(i).getStatus() == -1) {
				partlyOrders.add(listOrder.get(i));
			}
		}
		model.addAttribute("partlyOrders", partlyOrders);

		return "administrator/dispatchinofficeorders/adispatchinoffice";

	}

	@RequestMapping(value = "/sendtooffice", method = RequestMethod.GET)
	public String sendtooffice(Model model) {

		String status = "";
		final Long countOfOrders = 3L;
		model.addAttribute("countOfOrders", countOfOrders);

		List<Order> listOrder = orderService.getAll();
		List<Order> partlyOrders = new ArrayList<Order>();
		for (int i = 0; i < listOrder.size(); i++) {
			if (listOrder.get(i).getStatus() == -1) {
				partlyOrders.add(listOrder.get(i));
			}
		}
		if (partlyOrders.size() >= countOfOrders) {
			for (int i = 0; i < partlyOrders.size(); i++) {
				partlyOrders.get(i).setStatus(-2L);
				orderService.updateOrder(partlyOrders.get(i));
			}
			status = "ALL ORDERS SUCCESFULLY SENT TO THE PUBLISHER";
			partlyOrders = null;
		} else {
			status = "You should to collect at least "
					+ (3 - partlyOrders.size()) + " orders";
		}
		model.addAttribute("partlyOrders", partlyOrders);
		model.addAttribute("status", status);
		return "administrator/dispatchinofficeorders/adispatchinoffice";
	}
}
